package com.mystnihon.freeremote.loader.remote;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;

import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.util.Log;

import com.mystnihon.freeremote.util.NetworkConnection;
import com.mystnihon.freeremote.util.NetworkConnection.HttpMethod;
import com.mystnihon.freeremote.util.exception.NFRestClientException;
import com.mystnihon.freeremote.util.NetworkConnectionResult;
import com.mystnihon.loader.AbstractAsyncLoader;

/**
 * Loader to get the server time from the webservice.
 * 
 * @author Levi LIRVAT
 */
public class ServerLoader extends AbstractAsyncLoader<NetworkConnectionResult> {
	private static final int MAX_REDIRECT = 5;
	private String mUrl;
	private List<BasicNameValuePair> mParameters;
	private ArrayList<Header> mHeaders;
	private HttpMethod mNetworkMethod;
	private String mPostContent = null;
	private int mNumberOfRedirect = 0;
	private HttpContext mHttpContext;

	/**
	 * @param url
	 *            The URL to call the EPG.
	 */
	public ServerLoader(String url) {
		this(url, null);

	}

	/**
	 * @param url
	 *            The URL to call the EPG.
	 * @param parameters
	 *            d
	 */
	public ServerLoader(String url, List<BasicNameValuePair> parameters) {
		this(url, parameters, null);
	}

	/**
	 * @param url
	 *            The URL to call the EPG.
	 * @param parameters
	 *            d
	 * @param headers
	 *            dss
	 */
	public ServerLoader(String url, List<BasicNameValuePair> parameters, ArrayList<Header> headers) {
		this(url, parameters, null, NetworkConnection.HttpMethod.Get);
	}

	/**
	 * @param url
	 *            The URL to call the EPG.
	 * @param parameters
	 *            d
	 * @param headers
	 *            dss
	 * @param Network
	 *            method.
	 */
	public ServerLoader(String url, List<BasicNameValuePair> parameters, ArrayList<Header> headers,
			NetworkConnection.HttpMethod method) {
		mUrl = url;
		mParameters = parameters;
		mHeaders = headers;
		mNetworkMethod = method;
	}

	/**
	 * Set the post content for the request.
	 * 
	 * @param postContent
	 *            Post content
	 */
	public void setPostContent(String postContent) {
		mPostContent = postContent;
		mNetworkMethod = NetworkConnection.HttpMethod.Post;
	}

	public void setHttpContext(HttpContext lHttpContext) {
		mHttpContext = lHttpContext;
	}

	@Override
	protected boolean doLoad(Context ctx) {

		String userAgent = "Android";
		AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent);
		NetworkConnection cnt = new NetworkConnection(client);
		if (mHttpContext != null) {
			cnt.setHttpContext(mHttpContext);
		}
		if (mUrl == null && mUrl.length() == 0) {
			return false;
		}

		boolean value = handleUrl(cnt, mUrl, mNetworkMethod, mParameters, mPostContent, mHeaders, ctx, userAgent);

		client.close();

		return value;
	}

	private boolean handleUrl(NetworkConnection cnt, String url, NetworkConnection.HttpMethod method,
			List<BasicNameValuePair> parameters, String postContent, ArrayList<Header> headers, Context ctx, String userAgent) {
		NetworkConnectionResult result;
		if (postContent != null) {
			Log.i("NetworkConnection", "Post content : " + postContent);
		}
		try {
			result = cnt.retrieveStringAndHeadersFromService(url, method, parameters, postContent, headers, true,
					userAgent, false, ctx);
			mReturnData = result;
			return true;
		} catch (IllegalStateException e) {
			setErr(-1, e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			setErr(-1, e.getMessage());
			e.printStackTrace();
		} catch (URISyntaxException e) {
			setErr(-1, e.getMessage());
			e.printStackTrace();
		} catch (NFRestClientException e) {
			switch (e.mStatusCode) {
			case HttpStatus.SC_NOT_FOUND:
				setErr(-1, e.getMessage());
				e.printStackTrace();
				break;
			case HttpStatus.SC_MOVED_TEMPORARILY:

				if (mNumberOfRedirect < MAX_REDIRECT) {
					mNumberOfRedirect++;
					return handleUrl(cnt, e.getRedirectionUrl(), method, null, null, null, ctx, userAgent);
				}
				break;
			}
		}

		return false;
	}

	private void setErr(int i, String message) {
		// TODO Auto-generated method stub

	}

	protected void setErrorState() {
		mReturnData = null;

	}
}
